package com.sgb.merchant.view.fragment;

import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.tabs.TabLayout;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.MenuEntity;
import com.sgb.link.entity.merchant.InvestmentProjectEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.utils.CountMenuView;
import com.sgb.link.view.fragment.AppLazyFragment;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantFragmentMerchantHomeBinding;
import com.sgb.merchant.view.adapter.InvestmentProjectAdapter;
import com.sgb.merchant.viewmodel.MerchantHomeViewmodel;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.refresh.SuperSwipeRefreshLayout;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Time:2021/6/16
 * Author:黄淋
 * Description:
 */
public class MerchantHomeFragment extends AppLazyFragment implements SuperSwipeRefreshLayout.OnPullRefreshListener {
    MerchantFragmentMerchantHomeBinding mBinding;
    MerchantHomeViewmodel mViewModel;
    private InvestmentProjectAdapter mAdapter;
    private List<InvestmentProjectEntity> mListInvestment;
    Map<String, Object> mMap;
    private TextView textView;
    private boolean mIsLoadMore = false;
    private ArrayList<Fragment> mFragments;
    private SlidingFragmentPagerAdapter pagerAdapter;
    private String[] titles = {"投资项目", "投资需求"};
    private InvestmentFragment mInvestFragment;
    private InvestmentDemandFragment mDemandFragement;

    public static MerchantHomeFragment newInstance() {
        MerchantHomeFragment fragment = new MerchantHomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        isNeedSetComponent = 1;
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.merchant_fragment_merchant_home, container, false);
        mViewModel = new ViewModelProvider(this).get(MerchantHomeViewmodel.class);
        mBinding.tvMerchantHomeNeed.setOnClickListener(this::onClick);
        mBinding.tvMerchantHomePolicy.setOnClickListener(this::onClick);
        mBinding.swipeRefresh.setHeaderView(createHeaderView());
        mBinding.swipeRefresh.setOnPullRefreshListener(this);
        mBinding.appBarLayout.addOnOffsetChangedListener((appBarLayout, i) -> {
            if (i >= 0) {
                mBinding.swipeRefresh.setEnabled(true);
            } else {
                mBinding.swipeRefresh.setEnabled(false);
            }
        });
        return mBinding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        getMenu();
        initTabLayout();
        mListInvestment = new ArrayList<>();


    }


    @Override
    public void onClick(View view) {
        if (view.getId()==R.id.tv_merchant_home_need||view.getId()==R.id.tv_merchant_home_policy){
                MToast.showToast(getContext(), "功能开发中，敬请期待");
        }

    }

    /**
     * 获取顶部菜单
     */
    private void getMenu() {
        List<MenuEntity> list = new ArrayList<>();
        MenuEntity menuEntity1 = new MenuEntity();
        MenuEntity menuEntity2 = new MenuEntity();
        MenuEntity menuEntity3 = new MenuEntity();
        MenuEntity menuEntity4 = new MenuEntity();
        MenuEntity menuEntity5 = new MenuEntity();
        MenuEntity menuEntity6 = new MenuEntity();
        MenuEntity menuEntity7 = new MenuEntity();
        MenuEntity menuEntity8 = new MenuEntity();
        MenuEntity menuEntity9 = new MenuEntity();
        MenuEntity menuEntity10 = new MenuEntity();
        menuEntity1.setName("投资项目");
        menuEntity1.setHostImg(R.mipmap.merchant_touzixiangmu);
        menuEntity2.setName("投资需求");
        menuEntity2.setHostImg(R.mipmap.merchant_touzixuqiu);
        menuEntity3.setName("服务大厅");
        menuEntity3.setHostImg(R.mipmap.merchant_fuwudating_merchant);
        menuEntity4.setName("优惠政策");
        menuEntity4.setHostImg(R.mipmap.merchant_youhuizhengce);
        menuEntity5.setName("产业园区");
        menuEntity5.setHostImg(R.mipmap.merchant_chanyeyuanqu);
        menuEntity6.setName("资源优势");
        menuEntity6.setHostImg(R.mipmap.merchant_ziyuanyoushi);
        menuEntity7.setName("招商宣传");
        menuEntity7.setHostImg(R.mipmap.merchant_zhaoshangxuanchuan);
        menuEntity8.setName("专项通道");
        menuEntity8.setHostImg(R.mipmap.merchant_zhuanxiangtongdao);
        menuEntity9.setName("政府网站");
        menuEntity9.setHostImg(R.mipmap.merchant_zhengfuwangzhan);
        menuEntity10.setName("会议会展");
        menuEntity10.setHostImg(R.mipmap.merchant_huiyihuizhan);
        list.add(menuEntity1);
        list.add(menuEntity2);
        list.add(menuEntity3);
        list.add(menuEntity4);
        list.add(menuEntity5);
        list.add(menuEntity6);
        list.add(menuEntity7);
        list.add(menuEntity8);
        list.add(menuEntity9);
        list.add(menuEntity10);
        showMenuView(list);
    }

    public void showMenuView(List<MenuEntity> data) {
        mBinding.countMenu.initData(getChildFragmentManager(), data, new CountMenuView.OnItemClick() {
            @Override
            public void onItemClick(MenuEntity entity, int position) {
                switch (entity.getName()) {
                    case "投资项目":
                        ARouter.getInstance().build(PathMerchant.InvestmentProjectActivity).navigation();
                        break;
                    case "投资需求":
                        ARouter.getInstance().build(PathMerchant.DemandListActivity).navigation();
                        break;
                    case "产业园区":
                        ARouter.getInstance().build(PathMerchant.IndustryListActivity).navigation();
                        break;
                    default:
                        MToast.showToast(getContext(), "功能开发中，敬请期待");
                        break;
                }
            }
        });
    }

    private void initTabLayout() {
        mFragments = new ArrayList<>();
        mFragments.add(mInvestFragment=new InvestmentFragment());
        mFragments.add(mDemandFragement=new InvestmentDemandFragment());
        pagerAdapter = new SlidingFragmentPagerAdapter(getChildFragmentManager(), mFragments, titles);
        mBinding.viewPager.setAdapter(pagerAdapter);
        mBinding.viewPager.setOffscreenPageLimit(1);
        //取消tab点击效果
        mBinding.tabLayout.setTabRippleColor(ColorStateList.valueOf(getResources().getColor(R.color.transparent)));
        mBinding.tabLayout.setupWithViewPager( mBinding.viewPager);
        mBinding.tabLayout.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
               int tabPosition= tab.getPosition();
                if(tabPosition<2) {
                    mBinding.viewPager.setCurrentItem(tabPosition);
                    switch (tabPosition){
                        case 0:
                            mInvestFragment.refreshView();
                            break;
                        case 1:
                            mDemandFragement.refreshView();
                            break;
                    }
                }else{
                    MToast.showToast(getContext(), "功能开发中，敬请期待");
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mBinding.tabLayout2.addTab(mBinding.tabLayout2.newTab().setText("服务大厅"));
        mBinding.tabLayout2.addTab(mBinding.tabLayout2.newTab().setText("优惠政策"));
        //取消tab点击效果
        mBinding.tabLayout2.setTabRippleColor(ColorStateList.valueOf(getResources().getColor(R.color.transparent)));
        mBinding.tabLayout2.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                MToast.showToast(getContext(), "功能开发中，敬请期待");
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                MToast.showToast(getContext(), "功能开发中，敬请期待");
            }
        });
    }


    @SuppressLint("AutoDispose")
    @Override
    public void onRefresh() {
        textView.setText("正在刷新");

        Observable.timer(0, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_REFRESH));
                    mBinding.swipeRefresh.setRefreshing(false);
                });
    }

    @Override
    public void onPullDistance(int distance) {

    }

    @Override
    public void onPullEnable(boolean enable) {
        textView.setText(enable ? "释放立即刷新" : "下拉刷新");
    }

    private View createHeaderView() {
        @SuppressLint("InflateParams")
        View headerView = LayoutInflater.from(mBinding.swipeRefresh.getContext()).inflate(R.layout.super_swipe_refresh_head, null);
        ProgressBar progressBar = headerView.findViewById(R.id.pb_view);
        textView = headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        progressBar.setVisibility(View.GONE);
        return headerView;
    }




}
